package com.example.shiwu;

import static androidx.constraintlayout.motion.utils.Oscillator.TAG;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.ReceiveService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.ContextVariable;
import com.example.shiwu.util.CurveCharUtil;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.FileDownUtil;
import com.example.shiwu.util.SerialInter;
import com.example.shiwu.util.SocketUtils;
import com.example.shiwu.util.TitleSettingUtil;
import com.github.mikephil.charting.charts.LineChart;

import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ArrangeAddActivity extends AppCompatActivity implements SerialInter, AdapterView.OnItemSelectedListener {
    private Context myContext;
    public TextView title_text, title_setting;
    public ImageView title_back;
    public EditText arrange_type_val;
    public EditText arrange_electric_num_val;
    public EditText arrange_electric_distance_val;
    public EditText arrange_max_interval_val;
    private LineChart myChart;
    private ItemsService itemsService;
    private ArrangeService arrangeService;
    private ReceiveService receiveService;
    private Button arrange_btn_sub;
    private Spinner spin_one;
    private ArrayAdapter<String> arrayAdapter;
    private ImageView img;
    private Python py;
    private PyObject pyobj;
    public final int MSG_SUCCESS = 1;

    public Socket mSocket;
    private final int DEFAULT_PORT = 8086;
    private String mIpAddress = ContextVariable.IP; //服务端ip地址
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private static final String IP_ADDRESS = "ip_address";
    private static final String CLIENT_PORT = "client_port";
    private static final String CLIENT_MESSAGETXT = "client_msgtxt";
    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private static final int MSG_SOCKET_DISCONNECT = 5;
    private static final int MSG_SOCKET_CONNECT = 7;

    private static final int MSG_SOCKET_CONNECTFAIL = 8;
    private static final int MSG_SEND_DATA = 11;
    private static final int MSG_SEND_DATA_BYTE = 12;
    private static final int MSG_SEND_DATA_BYTE_RECEIVE = 13;//硬件成功返回信息
    private int mSocketConnectState = STATE_DISCONNECTED;
    private SocketReceiveThread mReceiveThread;
    private SocketConnectThread mConnectThread;
    private OutputStream mOutStream;
    private InputStream mInStream;
    private Handler mSubThreadHandler;
    private HandlerThread mHandlerThread;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS:
                    img.setImageBitmap(BitmapFactory.decodeByteArray((byte[]) msg.obj, 0, ((byte[]) msg.obj).length));
                    break;
                case MSG_SOCKET_CONNECT:
                    mSocketConnectState = STATE_CONNECTED;
                    System.out.println(R.string.disconnect);
//                    mReceiveThread = new SocketReceiveThread();
//                    mReceiveThread.start();
                    break;
                case MSG_SOCKET_DISCONNECT:
                    System.out.println(R.string.connect);
                    mSocketConnectState = STATE_DISCONNECTED;
                    closeConnection();
                    break;
                case MSG_SOCKET_CONNECTFAIL:
                    mSocketConnectState = STATE_DISCONNECTED;
                    System.out.println("======================连接失败=========================");
                    break;
            }
        }
    };

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.myContext = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.arrange_add);
        img = findViewById(R.id.array_img);
        //FileDownUtil.downLoadFile(this,FileDownUtil.DOWN_NAME+"1-38be0603875c401498157cef07318363.cvs","JY1.cvs");
        //startConnect();
        //initHandlerThraed();
        try {
            initPython(myContext, img);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        arrangeService = new ArrangeService();
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        title_setting = findViewById(R.id.title_setting);
        TitleSettingUtil.initTitle("排列设计", null, title_back, title_text, title_setting);
        arrange_btn_sub = findViewById(R.id.arrange_btn_sub);
        bindViews();
        arrange_type_val = findViewById(R.id.arrange_type_val);
        arrange_electric_num_val = findViewById(R.id.arrange_electric_num_val);
        arrange_electric_distance_val = findViewById(R.id.arrange_electric_distance_val);
        arrange_max_interval_val = findViewById(R.id.arrange_max_interval_val);
        arrange_max_interval_val.setFocusableInTouchMode(false);//不可编辑
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrangeAddActivity.this.finish();
            }
        });
        arrange_type_val.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(arrange_electric_num_val.getText().length() == 0){
                    return;
                }
                String type_val = String.valueOf(arrange_type_val.getText());
                String edit = String.valueOf(editable);
                if(!edit.equals("")) {
                    if (Integer.parseInt(edit) >= 0) {
                        if(type_val.equals("0") || type_val.equals("1")){//偶极-偶极、单极-偶极
                            String arrange_electric_num_val1 = String.valueOf((Integer.parseInt(String.valueOf(arrange_electric_num_val.getText())) - 3));
                            arrange_max_interval_val.setText(arrange_electric_num_val1);
                        } else if (type_val.equals("2") || type_val.equals("4")) {//温纳、温纳-斯伦贝谢
                            String arrange_electric_num_val1 = String.valueOf((int) Math.floor((Integer.parseInt(String.valueOf(arrange_electric_num_val.getText())) / 3) - 1));
                            arrange_max_interval_val.setText(arrange_electric_num_val1);
                        }else {//斯伦贝谢
                            String arrange_electric_num_val1 = String.valueOf((int) Math.floor((Integer.parseInt(String.valueOf(arrange_electric_num_val.getText())) / 2) - 1));
                            arrange_max_interval_val.setText(arrange_electric_num_val1);
                        }

                    }
                }

            }

        });
        arrange_electric_num_val.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String type_val = String.valueOf(arrange_type_val.getText());
                String edit = String.valueOf(editable);
                if(!edit.equals("")) {
                    if (Integer.parseInt(edit) > 1) {
                        if(type_val.equals("0") || type_val.equals("1")){//偶极-偶极、单极-偶极
                            String arrange_electric_num_val1 = String.valueOf((Integer.parseInt(String.valueOf(editable)) - 3));
                            arrange_max_interval_val.setText(arrange_electric_num_val1);
                        } else if (type_val.equals("2") || type_val.equals("4")) {//温纳、温纳-斯伦贝谢
                            String arrange_electric_num_val1 = String.valueOf((int) Math.floor((Integer.parseInt(String.valueOf(editable)) / 3) - 1));
                            arrange_max_interval_val.setText(arrange_electric_num_val1);
                        }else {//斯伦贝谢
                            String arrange_electric_num_val1 = String.valueOf((int) Math.floor((Integer.parseInt(String.valueOf(editable)) / 2) - 1));
                            arrange_max_interval_val.setText(arrange_electric_num_val1);
                        }

                    }
                }

            }

        });
        int countItem = findItemCount();
        if (countItem == 0) {

            arrange_btn_sub.setBackgroundResource(R.drawable.bg_blue_unselect);
            arrange_btn_sub.setEnabled(false);
        } else {
            initData(arrange_type_val, arrange_electric_num_val, arrange_electric_distance_val, arrange_max_interval_val);
            CurveCharUtil curveCharUtil = new CurveCharUtil();
            arrange_btn_sub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (arrange_type_val.getText().length() ==0){
                        Toast.makeText(myContext, "排列方式不能为空！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (arrange_electric_num_val.getText().length() ==0){
                        Toast.makeText(myContext, "电极总数不能为空！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (arrange_max_interval_val.getText().length() ==0){
                        Toast.makeText(myContext, "电极距离不能为空！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (arrange_electric_distance_val.getText().length() ==0){
                        Toast.makeText(myContext, "最大隔离系数不能为空！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (arrange_type_val.getText().length() > 0 &&
                            arrange_electric_num_val.getText().length() > 0 &&
                            arrange_max_interval_val.getText().length() > 0 &&
                            arrange_electric_distance_val.getText().length() > 0) {
                        Arrange arrange = new Arrange();
                        arrange.setDeviceType(Integer.parseInt(String.valueOf(arrange_type_val.getText())));
                        arrange.setElectrodeNum(String.valueOf(arrange_electric_num_val.getText()));
                        arrange.setInterval(String.valueOf(arrange_max_interval_val.getText()));
                        arrange.setElectrodeDistance(String.valueOf(arrange_electric_distance_val.getText()));
                        String typeVal = pyobj.callAttr("ERTuiArrayABMN", Integer.parseInt(String.valueOf(arrange_electric_num_val.getText())), Integer.parseInt(String.valueOf(arrange_max_interval_val.getText())),
                                Integer.parseInt(String.valueOf(arrange_electric_distance_val.getText())), Integer.parseInt(String.valueOf(arrange_type_val.getText()))).toJava(String.class);

                        String[] abmn1 = typeVal.split(",");
                        String abmn = typeVal.substring(typeVal.indexOf(")") + 2, typeVal.length());
                        String ns = abmn1[0];
                        String dtype = abmn1[1];
                        String shape = abmn1[2] + "," + abmn1[3];

                        arrange.setDeviceTypeVal(abmn);
                        arrange.setDeviceTypeLen(Integer.parseInt(ns));
                        arrange.setDtype(dtype);
                        arrange.setShape(shape);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                        Date date = new Date(System.currentTimeMillis());
                        arrange.setCreateTime(simpleDateFormat.format(date));
                        arrange.setUpdateTime(simpleDateFormat.format(date));
                        Items items = null;
                        try {
                            items = findSelectItem();
                            if (null != items) {
                                arrange.setItemId(items.getId());
                                Arrange arrange1 = new Arrange();
                                arrange1.setItemId(items.getId());
                                List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
                                if (arrangeLis.size() == 0) {
                                    boolean bl = arrangeService.save(arrange);
                                    if (bl) {
                                        byte[] bytesData = pyobj.callAttr("ERTuiArray", abmn, dtype, shape, Integer.parseInt(String.valueOf(arrange_electric_distance_val.getText())),arrange.getDeviceType(),String.valueOf(arrange_max_interval_val.getText())).toJava(byte[].class);
                                        //sendTxt("11,s;");

                                        Message msg = new Message();
                                        msg.what = MSG_SUCCESS;
                                        msg.obj = bytesData;
                                        mHandler.sendMessage(msg);
                                        Toast.makeText(myContext, "保存成功！", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    boolean bl = arrangeService.updade(arrange, new Arrange());
                                    if (bl) {
                                        byte[] bytesData = pyobj.callAttr("ERTuiArray", abmn, dtype, shape, Integer.parseInt(String.valueOf(arrange_electric_distance_val.getText())),arrange.getDeviceType(),String.valueOf(arrange_max_interval_val.getText())).toJava(byte[].class);
                                       // sendTxt("11,s;");
                                        Message msg = new Message();
                                        msg.what = MSG_SUCCESS;
                                        msg.obj = bytesData;
                                        mHandler.sendMessage(msg);
                                        Toast.makeText(myContext, "保存成功！", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                }
            });
        }

    }

    private void initPython(Context myContext, ImageView img) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();

        pyobj = py.getModule("ERT_UI_ARRAY");
        initImg();
    }

    private void bindViews() {
        spin_one = findViewById(R.id.arrange_type_spinner);
        spin_one.setOnItemSelectedListener(this);
        //设置选中后的布局，simple_spinner_item 是系统定义的布局，这里用系统的
        arrayAdapter = new ArrayAdapter<String>(this, R.layout.custom_spinner_item, getResources().getStringArray(R.array.modeData));
        //设置下拉框布局，simple_spinner_dropdown_item 是系统定义的布局，这里用系统的
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin_one.setAdapter(arrayAdapter);
        //设置默认选中项
        spin_one.setSelection(0, true);
    }

    private void initData(EditText arrange_type_val, EditText arrange_electric_num_val, EditText arrange_electric_distance_val, EditText arrange_max_interval_val) {
        Items items = findSelectItem();
        Arrange arrange = new Arrange();
        arrange.setItemId(items.getId());
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange);
        if (arrangeLis.size() > 0) {
            arrange_max_interval_val.setText(arrangeLis.get(0).getInterval());
            arrange_electric_num_val.setText(arrangeLis.get(0).getElectrodeNum());
            arrange_electric_distance_val.setText(arrangeLis.get(0).getElectrodeDistance());
            //arrange_type_val.setText(String.valueOf(arrangeLis.get(0).getDeviceType()));
            spin_one.setSelection(arrangeLis.get(0).getDeviceType());
        }
    }

    private Integer findItemCount() {
        itemsService = new ItemsService();
        List<Items> lis = itemsService.getItems(new Items());
        return lis.size();
    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        items.setStatus(1);
        List<Items> lis = itemsService.getItems(items);
        return lis.get(0);
    }

    public void initImg(){
        Items items = findSelectItem();
        Arrange arrange = new Arrange();
        arrange.setItemId(items.getId());
        arrangeService = new ArrangeService();
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange);
        if(arrangeLis.size()>0){
            //String abmn = arrangeLis.get(0).getDeviceTypeVal();
            String electric_distance = arrangeLis.get(0).getElectrodeDistance();
            String dtype = arrangeLis.get(0).getDtype();
            String shape = arrangeLis.get(0).getShape();
            String deviceType = String.valueOf(arrangeLis.get(0).getDeviceType());
            String typeVal = pyobj.callAttr("ERTuiArrayABMN", Integer.parseInt(arrangeLis.get(0).getElectrodeNum()), Integer.parseInt(arrangeLis.get(0).getInterval()),
                    Integer.parseInt(arrangeLis.get(0).getElectrodeDistance()),Integer.parseInt(deviceType) ).toJava(String.class);
//            String typeVal = pyobj.callAttr("ERTuiArrayABMN", Integer.parseInt(String.valueOf(arrange_electric_num_val.getText())), Integer.parseInt(String.valueOf(arrange_max_interval_val.getText())),
//                    Integer.parseInt(String.valueOf(arrange_electric_distance_val.getText())), Integer.parseInt(String.valueOf(arrange_type_val.getText()))).toJava(String.class);

           // String[] abmn1 = typeVal.split(",");
            String abmn = typeVal.substring(typeVal.indexOf(")") + 2, typeVal.length());
            byte[] bytesData = pyobj.callAttr("ERTuiArray", abmn, dtype, shape, Integer.parseInt(electric_distance),arrangeLis.get(0).getDeviceType(),arrangeLis.get(0).getInterval()).toJava(byte[].class);

            Message msg = new Message();
            msg.what = MSG_SUCCESS;
            msg.obj = bytesData;
            mHandler.sendMessage(msg);
        }

    }
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        System.out.println("spin_one111 ================================================================" + position);
        arrange_type_val.setText(position + "");
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        System.out.println("spin_one ================================================================" + spin_one.getPopupContext());
    }

    @Override
    public void connectMsg(String path, boolean isSucc) {

    }

    @Override
    public void readData(String path, byte[] bytes, int size) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            //closeConnection();
            //releaseSocket();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public  void releaseSocket(){
        //mReceiveThread.pause =true;
//        mReceiveThread.pauseThread();
//        mReceiveThread = null;
        //mReceiveThread.pause=true;

//        if (mOutStream != null) {
//            try {
//                mOutStream.close();
//
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            mOutStream = null;
//        }
//        if(mInStream!=null){
//            try {
//                mInStream.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            mInStream=null;
//        }

        if (mSocket != null) {
            try {
//                mSocket.close();
                mSocket.shutdownOutput();
                mSocket.shutdownInput();
            } catch (IOException e) {
            }
            mSocket = null;
        }

    }

    private void startConnect() {
        Log.i(TAG, "startConnect");
        if (mIpAddress == null || mIpAddress.length() == 0) {
            Toast.makeText(this, "请设置ip地址", Toast.LENGTH_LONG).show();
            return;
        }
        if (mSocketConnectState != STATE_DISCONNECTED) return;
        mConnectThread = new SocketConnectThread();
        mConnectThread.start();
        mSocketConnectState = STATE_CONNECTING;
    }
    private void initHandlerThraed() {
        //创建HandlerThread实例
        mHandlerThread = new HandlerThread("handler_thread");
        //开始运行线程
        mHandlerThread.start();
        //获取HandlerThread线程中的Looper实例
        Looper loop = mHandlerThread.getLooper();
        //创建Handler与该线程绑定。
        mSubThreadHandler = new Handler(loop) {
            public void handleMessage(Message msg) {
                Log.i(TAG, "mSubThreadHandler handleMessage thread:" + Thread.currentThread());
                switch (msg.what) {
                    case MSG_SEND_DATA:
                        writeMsg((String) msg.obj);
                        break;
                    case MSG_SEND_DATA_BYTE:
                        writeMsgByte((byte[]) msg.obj);
                    default:
                        break;
                }
            }
        };
    }

    public void closeConnection() {
        try {
            if (mOutStream != null) {
                mOutStream.close(); //关闭输出流
                mOutStream = null;
            }
            if (mInStream != null) {
                mInStream.close(); //关闭输入流
                mInStream = null;
            }
            if (mSocket != null) {
//                mSocket.close();  //关闭socket
//                mSocket = null;

                mSocket.shutdownInput();
                mSocket.shutdownOutput();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mReceiveThread != null) {
            mReceiveThread.pauseThread();
            mReceiveThread = null;
        }
        mSocketConnectState = STATE_DISCONNECTED;
    }

    private void sendTxt(String str) {
        if (mSocket == null) {
            Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show();
            return;
        }
        if (str.length() == 0)
            return;
        Message msg = new Message();
        msg.what = MSG_SEND_DATA;
        msg.obj = str;
        mSubThreadHandler.sendMessage(msg);
    }

    private void sendByte(byte[] str) {
        System.out.println("---------------------------------str----------------------------------------" + str);
        if (mSocket == null) {
            Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show();
            return;
        }
        if (str.length == 0)
            return;
        Message msg = new Message();
        msg.what = MSG_SEND_DATA_BYTE;
        msg.obj = str;
        msg.arg1 = MSG_SEND_DATA_BYTE_RECEIVE;//1 为硬件成功返回数据 弹出图表
        mSubThreadHandler.sendMessage(msg);
    }

    private void writeMsg(String msg) {
        Log.i(TAG, "writeMsg msg=" + msg);
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void writeMsgByte(byte[] msg) {
        Log.i(TAG, "------------------------------------------------writeMsgByte msg=" + msg);
        if (msg.length == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg);//发送
            mOutStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    class SocketConnectThread extends Thread {
        public void run() {
            try {
                //连接服务端，指定服务端ip地址和端口号。
                mSocket = new Socket(mIpAddress, mClientPort);
                if (mSocket != null) {
                    //获取输出流、输入流
                    mOutStream = mSocket.getOutputStream();
                    mInStream = mSocket.getInputStream();
                    sendTxt("22,S;");
                }
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTFAIL);
                return;
            }
            Log.i(TAG, "connect success");
            mHandler.sendEmptyMessage(MSG_SOCKET_CONNECT);
        }

    }

    class SocketReceiveThread extends Thread {
        private final Object lock = new Object();
        public boolean pause = false;

        /**
         * 调用这个方法实现暂停线程
         */
        void pauseThread() {
            pause = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        void resumeThread() {
            pause = false;
            //startPause = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            super.run();
            while (pause == false) {
                try {
                    byte[] buffer = new byte[1024];
                    this.resumeThread();

                    //读取数据，返回值表示读到的数据长度。-1表示结束
                    int count = mInStream.read(buffer);
                    if (count == -1) {
                        Log.i(TAG, "read read -1");
                        mHandler.sendEmptyMessage(MSG_SOCKET_DISCONNECT);
                        break;
                    } else {

                        String data = new String(buffer,0,count);
                        System.out.println("---- buffer = "+data);// 11,s;数据暂无 后续需存贮

                    }
                }catch (IOException e) {
                    //throw new RuntimeException(e);
                    e.printStackTrace();
                }
            }
        }

    }
}
